Grokking SQL for Tech Interviews
Rate this course
Ask Author
Contribute
Back to course home

1% completed

Vote For New Content
Introduction
Course Overview
What is RDBMS?
What is SQL?
A Quick Review of SQL
Read data from table
WHERE Clause
Operators
Handle NULLs in SQL
DISTINCT Clause
ORDER BY Clause
LIMIT and OFFSET
GROUP BY
HAVING
Aggregate Functions
Order of Execution
Order of SQL Query Execution
SQL Functions
Number Functions
String Functions
Date Functions
Nested Queries
Nested Query
Types of Subqueries
JOINS
Introduction
INNER JOIN
LEFT OUTER JOIN
RIGHT OUTER JOIN
FULL OUTER JOIN
SELF JOIN
SET Operations
What are SET operations?
UNION
INTERSECT
EXCEPT
A Quick Review of DDL
Keys in SQL
CREATE
ALTER
DROP
TRUNCATE
Indexes
A Quick Review of DML
INSERT
UPDATE
DELETE
Database Backup & Restore
Backup Database
Restore Database
Interview Problems - Easy
1. Major Cities
2. Not boring movies
3. Triangle Judgement
4. Biggest Single Number
5. Product Sales Analysis I
6. Product Sales Analysis II
7. Game Play Analysis I
8. Game Play Analysis II
9. Queries Quality and Percentage
10. Average Selling Price
11. Weather Type in Each Country
12. Students and Examinations
13. Ads Performance
14. Group Sold Products By The Date
15. Employee Email Verification
16. Sellers With No Sales
17. Average Time of Process
18. Find Followers Count
19. Ad-Free Sessions
20. Bikes Last Time Used
21. Daily User Engagement Levels
22. Employee Attendance Record
23. Library Book Loans
24. Customer Purchase Summary
25. Long Comments (Easy)
26. Unused Accounts
27. Patient Appointment No-Shows
28. Books and Authors
29. High School Attendance
30. Employee Absences
31. Green Product Identification (Easy)
32. Employee Department Exclusion (Easy)
33. Sales Person (Easy)
34. Employee Task Tracking (Easy)
Interview Problems - Medium
1. Winning Candidate
2. Second Degree Follower
3. 2nd Highest Salary
4. Game Play Analysis III
5. Game Play Analysis IV
6. Active Businesses
7. Product Price on a Specific Date
8. Monthly Transactions II
9. Team Scores in Football Tournament
10. Page Recommendations
11. Running Total for Different Genders
12. Evaluate Boolean Expression
13. Active Users
14. Find Interview Candidates
15. Suspicious Bank Accounts
16. Order Fulfillment Rate (Medium)
17. Last Person to Fit in the Elevator (Medium)
18. Retail Expansion Analysis (Medium)
19. Employee Collaboration Networks (Medium)
20. Second Fastest Time in Races (Medium)
Interview Problems - Hard
1. Trips and Users
2. Human Traffic of Stadium
3. Students Report By Geography
4. Game Play Analysis V
5. Number of Transactions per Visit
6. Find the Quiet Students in All Exams
7. First and Last Call On the Same Day
8. Build the Equation
9. Longest Winning Streak
10. Dynamic Pivoting of a Table
11. Dynamic Unpivoting of a Table
12. Generate the Invoice
13. Popularity Percentage
14. Viewers Turned Streamers
15. Status of Flight Tickets
Test Your Knowledge
1. High Performing Employees (Easy)
2. Student Course Averages (Easy)
3. Library Book Checkout Percentage (Easy)
4. Employee Performance and Improvement Rate (Easy)
5. Find Popular Posts (Easy)
6. Main Office Assignment for Each Employee (Easy)
7. Rectangle Validation (Easy)
8. Library Book Checkouts by Date (Easy)
9. Same-Day Appointment Fulfillment (Medium)
10. Departments with High Earning Employees (Medium)
11. Students Who Attended All Courses (Medium)
12. Library Book Checkouts First Year (Medium)
13. Repeated Values in Sequence (Medium)
14. School Top Achievers by Subject (Hard)
4. Employee Performance and Improvement Rate (Easy)

Problem Statement

Table: Performance
Each row in this table represents a performance evaluation of an employee, detailing the employee's name, the evaluation result, the evaluation round, and the performance score.

+----------------+---------+
| Column Name    | Type    |          
+----------------+---------+
| employee_name  | varchar |           
| evaluation     | varchar |       
| round          | int     |          
| score          | int     |    
+----------------+---------+
This table may have duplicate rows.
This table contains information collected from performance evaluations of employees.
The round column has a value from 1 to 10.
The score column has a value from 1 to 100. An evaluation with a score less than 50 is considered a poor evaluation.

Develop a solution to find each employee_name, their performance, and improvement_rate.

We define employee performance as:

  • The average of the ratio between employee evaluation score and its round.

We also define improvement rate as:

  • The percentage of all evaluations with a score improvement over the previous rounds, and are greater than 50.

Both performance and improvement_rate should be rounded to 2 decimal places.

Return the result table in any order.

Example

Input:

Performance table: +---------------+-------------+-------+-------+ | employee_name | evaluation | round | score | +---------------+-------------+-------+-------+ | Alice | Efficiency | 1 | 80 | | Alice | Productivity| 2 | 90 | | Alice | Creativity | 3 | 60 | | Bob | Efficiency | 1 | 40 | | Bob | Productivity| 2 | 60 | | Bob | Creativity | 3 | 70 | +---------------+-------------+-------+-------+

Output:

+---------------+-----------+-------------------+ | employee_name | performance | improvement_rate | +---------------+-----------+-------------------+ | Alice | 48.33 | 33.33 | | Bob | 31.11 | 66.67 | +---------------+-----------+-------------------+

Output Explanation

Step 1: Calculate Employee Performance

For each employee:

  1. Divide the score by the round for all evaluations.
  2. Calculate the average of these ratios.
  • Alice:

  • Bob:

Step 2: Calculate Improvement Rate

For each employee:

  1. Check if the score in each round:

    • Is greater than 50.
    • Is greater than the score in the previous round.
  2. Count the number of evaluations that meet the criteria.

  • Alice:

    • Round 1: 80 (No previous round, does not count).
    • Round 2: 90 (Improved and >50).
    • Round 3: 60 (Not improved but >50).
    • Total: 1 improvement out of 3 evaluations.
  • Bob:

    • Round 1: 40 (No previous round, does not count).
    • Round 2: 60 (Improved and >50).
    • Round 3: 70 (Improved and >50).
    • Total: 2 improvements out of 3 evaluations.

Try It Yourself

MYSQL

. . . .

Performance =

Solution

To solve this problem, we need to calculate each employee's performance and improvement rate based on their evaluation scores across different rounds. The approach involves systematically breaking down the problem into manageable steps, utilizing SQL window functions and aggregation techniques to derive the required metrics.

  • Calculate Performance: Determine the average ratio of each employee's score to the corresponding evaluation round.
  • Determine Improvement Rate: Identify the percentage of evaluations where an employee's score improved compared to the previous round and is greater than 50.
  • Round the Results: Ensure that both performance and improvement rate are rounded to two decimal places for precision.

SQL Query

WITH LaggedPerformance AS ( SELECT employee_name, round, score, LAG(score) OVER (PARTITION BY employee_name ORDER BY round) AS previous_score FROM Performance ) SELECT employee_name, ROUND(AVG(score * 1.0 / round), 2) AS performance, ROUND( (SUM(CASE WHEN score > 50 AND previous_score IS NOT NULL AND score > previous_score THEN 1 ELSE 0 END) * 100.0 / COUNT(*)), 2 ) AS improvement_rate FROM LaggedPerformance GROUP BY employee_name;

Step-by-Step Approach

Step 1: Calculate Performance

Compute the average of the ratio between each employee's score and the evaluation round to assess overall performance.

SQL Query:

SELECT employee_name, AVG(score * 1.0 / round) AS performance FROM Performance GROUP BY employee_name;

Explanation:

  • AVG(score * 1.0 / round):
    • Calculates the average of the score divided by the round number for each employee.
    • Multiplying by 1.0 ensures that the division is performed using floating-point arithmetic, preserving decimal values.
  • GROUP BY employee_name:
    • Aggregates the calculations for each employee individually.

Output After Step 1:

+---------------+-------------+ | employee_name | performance | +---------------+-------------+ | Alice | 48.3333333 | | Bob | 31.111111 | +---------------+-------------+

Step 2: Determine Improvement Rate

Calculate the percentage of evaluations where an employee's score improved compared to the previous round and is greater than 50.

SQL Query:

WITH LaggedPerformance AS ( SELECT employee_name, round, score, LAG(score) OVER (PARTITION BY employee_name ORDER BY round) AS previous_score FROM Performance ) SELECT employee_name, ROUND( (SUM(CASE WHEN score > 50 AND previous_score IS NOT NULL AND score > previous_score THEN 1 ELSE 0 END) * 100.0 / COUNT(*)), 2 ) AS improvement_rate FROM LaggedPerformance GROUP BY employee_name;

Explanation:

  • WITH LaggedPerformance AS (...):
    • Creates a Common Table Expression (CTE) that adds a column previous_score representing the score from the previous round for each employee.
  • LAG(score) OVER (PARTITION BY employee_name ORDER BY round):
    • Retrieves the score from the preceding round for each employee, enabling comparison between consecutive rounds.
  • SUM(CASE WHEN ... THEN 1 ELSE 0 END):
    • Counts the number of evaluations where:
      • The current score is greater than 50.
      • There is a valid previous_score (i.e., not the first round).
      • The current score is higher than the previous_score.
  • (SUM(...) * 100.0 / COUNT(*)):
    • Calculates the improvement rate as a percentage by dividing the count of improved evaluations by the total number of evaluations for each employee.
  • ROUND(..., 2):
    • Rounds the improvement rate to two decimal places.

Output After Step 2:

+---------------+-------------------+ | employee_name | improvement_rate | +---------------+-------------------+ | Alice | 33.33 | | Bob | 66.67 | +---------------+-------------------+

Step 3: Combine Performance and Improvement Rate

Objective:
Merge the performance and improvement rate calculations to present a consolidated view for each employee.

SQL Query:

WITH LaggedPerformance AS ( SELECT employee_name, round, score, LAG(score) OVER (PARTITION BY employee_name ORDER BY round) AS previous_score FROM Performance ) SELECT employee_name, ROUND(AVG(score * 1.0 / round), 2) AS performance, ROUND( (SUM(CASE WHEN score > 50 AND previous_score IS NOT NULL AND score > previous_score THEN 1 ELSE 0 END) * 100.0 / COUNT(*)), 2 ) AS improvement_rate FROM LaggedPerformance GROUP BY employee_name;

Explanation:

  • Combining CTE and Aggregations:
    • The CTE LaggedPerformance is used to access both the current and previous scores within the same query.
  • Calculating Performance and Improvement Rate Simultaneously:
    • AVG(score * 1.0 / round) computes the performance metric.
    • The SUM(CASE ...) construct calculates the number of improved evaluations, which is then converted into a percentage to represent the improvement rate.
  • Rounding the Results:
    • Both performance and improvement_rate are rounded to two decimal places for clarity and consistency.

Final Output:

+---------------+-------------+-------------------+ | employee_name | performance | improvement_rate | +---------------+-------------+-------------------+ | Alice | 48.33 | 33.33 | | Bob | 31.11 | 66.67 | +---------------+-------------+-------------------+
3. Library Book Checkout Percentage (Easy)
5. Find Popular Posts (Easy)
Mark as Completed

On this page

Problem Statement

Example

Input:

Output:

Output Explanation

Try It Yourself

Solution

SQL Query

Step-by-Step Approach